package pers.cz.chat.filter;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.chat.UserManager;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;

/**
 * @version 1.0
 * @description: 登录消息拦截器
 * @author: ChengZhi 0336
 * @create: 2025-01-06 18:11
 **/
public class LoginFilter implements FilterHandler<Message, Channel> {

	private Logger logger = LoggerFactory.getLogger(LoginFilter.class);


	@Override
	public boolean approve(Message message, Channel channel, FilterHandlerContext<Message, Channel> handlerContext) {
		if (MsgType.AUTH == message.getMsgType()) {
			// 如果为认证消息
			String username = message.getAttachment("username");
			String password = message.getAttachment("password");

			if (UserManager.userAuth(username, password)) {
				logger.info("{}登录成功!", username);
				UserManager.markOnline(username, channel);

				Message loginSuccessMessage = new Message();
				loginSuccessMessage.setMsgType(MsgType.AUTH);
				loginSuccessMessage.addAttachment("source", "server");
				loginSuccessMessage.addAttachment("target", username);
				loginSuccessMessage.addAttachment("result", "success");
				loginSuccessMessage.setContent(username + "登录成功！");
				channel.writeAndFlush(loginSuccessMessage);
				return true;
			} else {
				logger.info("{}登录失败!", username);
				Message loginSuccessMessage = new Message();
				loginSuccessMessage.setMsgType(MsgType.AUTH);
				loginSuccessMessage.addAttachment("source", "server");
				loginSuccessMessage.addAttachment("target", username);
				loginSuccessMessage.addAttachment("result", "fail");
				loginSuccessMessage.setContent(username + "登录失败！");
				channel.writeAndFlush(loginSuccessMessage);
				channel.close();
			}
		}
		return handlerContext.doFilter(message, channel);
	}
}
